<template>
  <div>
    <div v-if="userName">{{userName}}</div>
    <div v-else @click="login">GITHUB LOGIN</div>
  </div>
</template>

<script>
export default {
  name: "Home",
  components: {},
  data() {
    return {
      preventHref: "", //授权前的页面链接
      userName: "",
      code: "",
    };
  },
  // 保存授权前的页面链接
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不！能！获取组件实例 `this`
    // 因为当守卫执行前，组件实例还没被创建
    window.sessionStorage.preventHref = from.fullPath;
    next();
  },
  created() {
    this.userName = window.sessionStorage.getItem("name") || "";
    this.code = this.$route.query.code;
    if (this.code) {
      this.getUserInfo();
    }
  },
  mounted() {},
  methods: {
    async login() {
      let res = await this.axios({
        method: "get",
        url: "/api/github/login",
        params: {
          path: "http://localhost:8082" + this.$route.fullPath,
        },
      });
      //window.open(url,"newwindown","height=400, width=500, top=20%, left=30%, toolbar=no, menubar=no,scrollbars=no, resizable=no,location=n o, status=no");
      window.open(res.data, "_self");
    },
    //获取用户信息
    async getUserInfo() {
      let res = await this.axios.get(
        "http://127.0.0.1:8080/github/callback?code=" + this.code
      );
      //保存用户信息
      window.sessionStorage.setItem("name", res.data.login);
      //跳转回授权前的页面链接
      this.$router.push(window.sessionStorage.preventHref);
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
